package org.smart4j.framework;

import org.apache.commons.lang3.StringUtils;
import org.smart4j.framework.bean.*;
import org.smart4j.framework.helper.BeanHelper;
import org.smart4j.framework.helper.ConfigHelper;
import org.smart4j.framework.helper.ControllerHelper;
import org.smart4j.framework.util.ClassUtil;
import org.smart4j.framework.util.JsonUtil;
import org.smart4j.framework.util.ReflectionUtil;
import org.smart4j.framework.util.StreamUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lin on 2018/04/16.
 */
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {
    @Override
    public void init(ServletConfig config) throws ServletException {
        HelpLoader.init();
        ServletContext servletContext = config.getServletContext();
        ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
        jspServlet.addMapping(ConfigHelper.getAppJspPath() + "*");
        ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
        defaultServlet.addMapping(ConfigHelper.getAppAssetPath() + "*");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String requestMethod = req.getMethod().toLowerCase();
        String requestPath = req.getPathInfo();
        Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
        if (handler != null) {
            Class<?> controllerClass = handler.getControllerClass();
            Object controllerBean = BeanHelper.getBean(controllerClass);
            Enumeration<String> paramNames = req.getParameterNames();
            Map<String, Object> paramMap = new HashMap<String, Object>();
            while (paramNames.hasMoreElements()){
                String paramName = paramNames.nextElement();
                paramMap.put(paramName, req.getParameter(paramName));
            }
            String body = StreamUtil.getString(req.getInputStream());
            if(!StringUtils.isEmpty(body)) {
                String[] params = StringUtils.split(body, "&");
                for (String param : params) {
                    String[] array = StringUtils.split(param, "=");
                    if(array != null && array.length == 2){
                        paramMap.put(array[0], array[1]);
                    }
                }
            }
            Param param = new Param(paramMap);
            Object result = ReflectionUtil.invokeMethod(controllerBean, handler.getMethod(), param);
            if(result instanceof View) {
                View view = (View)result;
                String path = view.getPath();
                if(!StringUtils.isEmpty(path)){
                    if(path.startsWith("/")){
                        resp.sendRedirect(req.getContextPath() + path);
                    } else {
                        Map<String, Object> model = view.getModel();
                        for(String key : model.keySet()) {
                            req.setAttribute(key, model.get(key));
                        }
                        req.getRequestDispatcher(ConfigHelper.getAppJspPath() + path).forward(req,resp);
                    }
                }
            } else if(result instanceof Data) {
                Data data = (Data)result;
                Object model = data.getModel();
                if(model != null) {
                    resp.setContentType("application/json");
                    resp.setCharacterEncoding("utf-8");
                    PrintWriter writer = resp.getWriter();
                    writer.write(JsonUtil.toJSON(model));
                    writer.flush();
                    writer.close();
                }
            }
        }

    }
}
